package com.naizhuai.ui.home;


import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.naizhuai.Model.AccountHelper;
import com.naizhuai.R;
import com.naizhuai.ui.BaseFragment;
import com.naizhuai.ui.adapter.GridSpacingItemDecoration;
import com.naizhuai.ui.components.MarqueeTextView;
import com.naizhuai.ui.components.MultStateView;
import com.naizhuai.ui.entity.Bus.Bus;
import com.naizhuai.ui.entity.NoticeAndBanner;
import com.naizhuai.ui.entity.RecommendScheme;
import com.naizhuai.ui.loopviewpager.AutoLoopViewPager;
import com.naizhuai.ui.viewpagerindicator.CirclePageIndicator;
import com.naizhuai.util.NaizhuAILog;
import com.naizhuai.util.RxBus;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import rx.functions.Action1;


public class HomeFragment extends BaseFragment implements HomeContract.View {
    @BindView(R.id.pager)
    AutoLoopViewPager mAutoLoopViewPager;
    @BindView(R.id.indicator)
    CirclePageIndicator indicator;
    Unbinder unbinder;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.frag_recommend)
    RecyclerView fragRecommend;
    @BindView(R.id.marqueeText)
    MarqueeTextView marqueeText;
    HomeContract.Presenter mPresenter;
    @BindView(R.id.container_State)
    MultStateView ContainerState;
    private BrightpointsAdapter mBrightpointsAdapter;
    public HomeFragment() {
        // Required empty public constructor
    }

    public static HomeFragment newInstance() {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        }

    }


    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        unbinder = ButterKnife.bind(this, view);

        return view;
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mPresenter = new HomePresenter();
        mPresenter.takeView(this);
        InitView();
        accordingToPowerLoadData(true);


    }

    private void accordingToPowerLoadData(boolean isload) {
        if (TextUtils.isEmpty(AccountHelper.getComPanyid())){
            ContainerState.showView(MultStateView.STATUS_NOPOWER);
        }else {
            ContainerState.showView(MultStateView.STATUS_CONTENT);
            if (isload)
             refreshLayout.autoRefresh();
        }
    }


    private  boolean isReceive;


    @Override
    public void onPause() {
        super.onPause();
        isReceive=false;
    }

    @Override
    public void onResume() {
        super.onResume();
        NaizhuAILog.d("onResumeHome");
//        accordingToPowerLoadData(false);
        isReceive=true;
        RxBus.getDefault().toObservableSticky(Bus.UserChange.class)
                .subscribe(new Action1<Bus.UserChange>() {
                    @Override
                    public void call(Bus.UserChange userChange) {
                        if (isReceive){
                            decrementcount();
                            accordingToPowerLoadData(true);
                            if (getcount()==0){
                                RxBus.getDefault().removeStickEvent(Bus.UserChange.class);
                                reset();
                            }
                        }
                    }
                });

    }

    private void InitView() {
        initNoticeBoard();
        InitFragRecommend();
        refreshLayout.setOnLoadmoreListener(refreshlayout ->
                mPresenter.loadMoreBirghtPoint()
        );
        refreshLayout.setOnRefreshListener(refreshlayout ->
                mPresenter.loadMainPage()
        );
    }

    private void initNoticeBoard() {
        marqueeText.setTextColor(R.color.lightorange);
    }


    /**
     * Article内容列表
     */
    private void InitFragRecommend() {
        fragRecommend.setNestedScrollingEnabled(false);
        fragRecommend.addItemDecoration(new GridSpacingItemDecoration(2, getResources().getDimensionPixelSize(R.dimen.sub_medium_spacing), false));
        fragRecommend.setLayoutManager(new GridLayoutManager(getContext(), 2));
        fragRecommend.setAdapter(mBrightpointsAdapter = new BrightpointsAdapter());
    }


    /**
     * 初始化广告栏的数据 后期会支持视频直播和音频直播
     * 展示内容：
     * 1、重要的内容（公司通知、特殊活动）；
     * 2、广告内容，供应商广告连接（后期）；
     * 3、比较优秀的问题文章；
     * 4、视频直播、音频直播等（后期）。
     */
    private void InitBanner(List<NoticeAndBanner> bannerItemList) {
        if (bannerItemList == null || bannerItemList.size() == 0) {
            return;
        }
        GalleryPagerAdapter galleryAdapter = new GalleryPagerAdapter(getActivity(), bannerItemList);
        mAutoLoopViewPager.setAdapter(galleryAdapter);
        indicator.setPadding(5, 5, 10, 5);
        indicator.setViewPager(mAutoLoopViewPager);
    }


    private class GalleryPagerAdapter extends PagerAdapter {
        private Context mContext;
        private List<NoticeAndBanner> mBannerList = Collections.EMPTY_LIST;

        GalleryPagerAdapter(Context context, List<NoticeAndBanner> bannerList) {
            this.mContext = context;
            this.mBannerList = bannerList;
        }

        @Override
        public int getCount() {
            return mBannerList.size();
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, int position) {
            ImageView item = new ImageView(mContext);
            final NoticeAndBanner banner = mBannerList.get(position);
            ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(-1, -1);
            item.setLayoutParams(params);
            item.setScaleType(ImageView.ScaleType.FIT_XY);
            //这两个是变化的
            Glide.with(mContext).load(banner.message).into(item);
            item.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    shortToast("点击了Banner");
                }
            });

            container.addView(item);
            return item;
        }

        @Override
        public void destroyItem(@NonNull ViewGroup collection, int position, @NonNull Object view) {
            collection.removeView((View) view);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        marqueeText.recycle();
        unbinder.unbind();
    }

    @Override
    public void showBanner(List<NoticeAndBanner> bannerItemList) {
        InitBanner(bannerItemList);
    }

    @Override
    public void showNotice(List<NoticeAndBanner> noticeList) {
        if (noticeList == null || noticeList.size() == 0) {
            return;
        }

        List<String> strings = new ArrayList<>();
        for (NoticeAndBanner notice : noticeList) {
            strings.add(notice.message);
        }
        marqueeText.initTextDatas(strings);
        marqueeText.setClickCallBack(position -> {
            NoticeAndBanner notice = noticeList.get(position);
            shortToast(notice.message);
        });
    }

    @Override
    public void showBirghtPoints(List<RecommendScheme> schemeList, boolean isadd) {
        if (isadd) {
            mBrightpointsAdapter.addItemList(schemeList);
        } else {
            mBrightpointsAdapter.setItemList(schemeList);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        NaizhuAILog.d("onAttach");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        NaizhuAILog.d("onDetach");
    }

    @Override
    public void showFailMsg(String errorMsg) {
        shortToast(errorMsg);
    }

    @Override
    public void stopRefresh() {
        if (refreshLayout.isLoading()) {
            refreshLayout.finishLoadmore();
        }
        if (refreshLayout.isRefreshing()) {
            refreshLayout.finishRefresh();
        }
    }

}
